package com.cmict.data.infra.recipient;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.cmict.data.framework.common.util.collection.CollectionUtils;
import com.cmict.data.infra.api.emus.NotifyRecipientFilterTypeEnum;
import com.cmict.data.system.api.dept.DeptApi;
import com.cmict.data.system.api.dept.dto.DeptRespDTO;
import com.cmict.data.system.api.user.AdminUserApi;
import com.cmict.data.system.api.user.dto.AdminUserRespDTO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Hccake 2020/12/21
 * @version 1.0
 */
@Service
public class SpecifyDeptRecipientFilter implements RecipientFilter {

    @Resource
	private  AdminUserApi adminUserApi;
    @Lazy
    @Resource
	private   DeptApi deptApi;

	/**
	 * 当前筛选器对应的筛选类型
	 * @return 筛选类型对应的标识
	 * @see NotifyRecipientFilterTypeEnum
	 */
	@Override
	public Integer filterType() {
		return NotifyRecipientFilterTypeEnum.SPECIFY_DEPT.getValue();
	}

	/**
	 * 接收者筛选
	 * @param filterCondition 筛选条件
	 * @return 接收者集合
	 */
	@Override
	public List<AdminUserRespDTO> filter(List<Long> filterCondition) {
		return adminUserApi.getUserMapByDeptIds(filterCondition).values().stream().collect(Collectors.toList());
	}

	/**
	 * 获取当前用户的过滤属性
	 * @param adminUserRespDTO 系统用户
	 * @return 该用户所对应筛选条件的属性
	 */
	@Override
	public Object getFilterAttr(AdminUserRespDTO adminUserRespDTO) {
		return adminUserRespDTO.getDeptId();
	}

	/**
	 * 是否匹配当前用户
	 * @param filterAttr 筛选属性
	 * @param filterCondition 筛选条件
	 * @return boolean true: 是否匹配
	 */
	@Override
	public boolean match(Object filterAttr, List<Object> filterCondition) {
		Integer organizationId = (Integer) filterAttr;
		return filterCondition.stream().map(Integer.class::cast).anyMatch(x -> x.equals(organizationId));
	}

	@Override
	public JSONArray filterInfo(List<Long> filterCondition) {
		List<DeptRespDTO> depts = deptApi.getDeptMapByListIds(filterCondition).values().stream().collect(Collectors.toList());
        return JSONArray.parseArray(JSON.toJSONString(depts));
	}

}
